//-----------------1、封装原生ajax工具函数-----------------------------------

function ajax(options) {

    // 1.创建xmlHttpRequest对象
    const xhr = new window.XMLHttpRequest

    //2.处理参数，对象转为名称值对形式  username='admin'
    let parame = formateParame(options.data)
    //3.判断请求
    let method = options.method.toUpperCase() //小转大
    if (method == 'GET') {
        xhr.open(method, options.url + '?' + parame)
        xhr.send()
    } else if (method == 'POST') {
        xhr.open(method, options.url)
        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
        xhr.send(parame)
    }

    //6. 处理响应结果
    xhr.onreadystatechange = () => {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                let result = xhr.responseText
                let data = JSON.parse(result)
                //调用处理成功的回调函数success
                options.success(data)
            } else {
                options.error(xhr.status)
            }
        }
    }

}

//对象转为名称值对形式 --> username='admin'
function formateParame(obj) {
    let arr = []
    for (let key in obj) {
        let item = `${key}=${obj[key]}`
        arr.push(item)
    }
    let str = arr.join('&')
    return str
}

//------------------------2、promise封装ajax---------------------------------
function ajaxPromise(obj) {
    const promise = new Promise(function (resolve, reject) {
        ajax({
            method: obj.method,
            url: obj.url,
            data: obj.data,
            success: function (data) {
                resolve(data)
            },
            error: function (error) {
                reject(error)
            }
        })
    })
    //局部作用域-->用return解决
    return promise
}


//------------------------3、cookie封装-----------------------------------

//保存cookie
function saveCookie(key, value, expires) {
    // document.cookie = 'b=200;expires = Thu,18 Dec2022 12:00:00 GMT'
    let time = new Date()
    // 设置毫秒
    time.setTime(time.getTime() + expires - 8 * 60 * 60 * 1000)
    document.cookie = `${key}=${value};expires=${time}`
}

/*获取cookie
    'username=admin; password=123; age=33'
*/
function getCookie(key) {
    let cookieStr = document.cookie
    let cookieArr = cookieStr.split(';')
    let value
    cookieArr.forEach(item => {
        let arr = []
        arr.push(item.substring(0, item.indexOf('=')))
        arr.push(item.substring(item.indexOf('=') + 1))

        if (arr[0].trim() == key) {
            value = arr[1]
        }
    })
    return value
}

/*
    删除cookie
*/
function deleteCookie(key) {
    saveCookie(key, 1, -1)
}


// 传参
// ajaxPromise({
//     method: 'get',
//     url: 'http://www.xiongmaoyouxuan.com/api/tab/2?start=0'
// }).then(data => {
//    console.log('data')
// }).catch(error => {
//     console.log('网络请求出错')
// })